﻿#include "WeaponItem.h"
#include "cocostudio/CocoStudio.h"
using namespace cocos2d;
using namespace cocos2d::ui;
WeaponItem::WeaponItem(int index):index(index) {

}

WeaponItem::~WeaponItem() {

}

WeaponItem* WeaponItem::create(int index) {
	WeaponItem* ret = new (std::nothrow) WeaponItem(index);
	if (ret && ret->init()) {
		ret->autorelease();
		return ret;
	}
	CC_SAFE_DELETE(ret);
	return nullptr;
}

bool WeaponItem::init() {
	if (!Widget::init()) {
		return false;
	}
	initSpriteFrameCache();
	//加载csb文件
	Node* root = CSLoader::createNode("scenes/start/layer/items/weaponItem.csb");
	this->addChild(root);

	//获取人物头像图片
	Sprite* Image_player = dynamic_cast<Sprite*>(root->getChildByName("weapon"));

	//选中
	selected = dynamic_cast<Sprite*>(root->getChildByName("selected"));
	selected->setVisible(false);

	//根据值改变图片 参数:图片路径
	char filename[80];
	//Sprite* test = Sprite::createWithSpriteFrame(gameSpriteCache->getSpriteFrameByName("prop_1.png"));
	sprintf_s(filename, "weapon_%d.png", index);
	auto test = gameSpriteCache->getSpriteFrameByName(filename);
	Image_player->setSpriteFrame(test);

	//获取背景按钮，设置吞噬触摸为false
	bgBtn = dynamic_cast<Button*>(root->getChildByName("bgBtn"));
	bgBtn->setSwallowTouches(false);
	return true;
}

/*
	加载精灵帧缓存
*/
void WeaponItem::initSpriteFrameCache() {
	gameSpriteCache = SpriteFrameCache::getInstance();
	gameSpriteCache->addSpriteFramesWithFile("scenes/start/image/weapons_ui.plist",
		Director::getInstance()->getTextureCache()->addImage(
			"scenes/start/image/weapons_ui.png"));		//向帧缓冲中添加纹理图片
}


void WeaponItem::setSelected(bool isSelect) {
	selected->setVisible(isSelect);
	if (isSelect == true) {
		UserDefault::getInstance()->setIntegerForKey("selected", index);
	}
}

void WeaponItem::addClickEventListener(const ccWidgetClickCallback& callback) {
	bgBtn->addClickEventListener(callback);
}